//
//  NewBookMallVC.m
//  LiteraryTune
//
//  Created by Mr.Xy on 2018/11/21.
//  Copyright © 2018 cxd. All rights reserved.
//

#import "NewBookMallVC.h"
#import "BookMallMainCell.h"
#import "HomeMenuModel.h"
#import "BookDetailModel.h"
#import "BookCollectCell.h"
#import "RecommendCollectionReusableView.h"
#import "FooterCollectionReusableView.h"
#import "BookMallBannerHeader.h"
#import "RecommendBookVC.h"
#import "RankBookVC.h"
#import "BookNeewVC.h"
#import "MallBookViewController.h"
#import "MallListenViewController.h"
#import "PeriodicalViewController.h"
#import "MallNewspaperViewController.h"
#import "VoiceBookViewController.h"
#import "ReadAppBookFirendVC.h"
#import "BookDetailShowViewController.h"
#import <SDCycleScrollView.h>
#import "ScanQRCodeVC.h"

@interface NewBookMallVC () <UICollectionViewDelegate, UICollectionViewDataSource, SDCycleScrollViewDelegate, UICollectionViewDelegateFlowLayout>

@property (strong, nonatomic) SDCycleScrollView *bannerView;

@property (strong, nonatomic) UICollectionView *mainCollectionView;

// 推荐图书
@property (nonatomic, strong)NSArray *recommentArray;
// 阅读榜
@property (nonatomic, strong)NSArray *rankArray;
// 新书上架
@property (nonatomic, strong)NSArray *BookNewArray;
// 频道按钮
@property (strong, nonatomic) NSArray<HomeMenuModel *> *modelsArray;

@end

@implementation NewBookMallVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
    
    [self loadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.bannerView adjustWhenControllerViewWillAppera];
    
    [self.navigationController setNavigationBarHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    [self.mainCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
}

#pragma mark - UI
- (void)setupUI {
    
    [self setupBanner];
    [self setupCollection];
}

- (void)setupBanner {
    
    self.bannerView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectZero delegate:self placeholderImage:nil];
    self.bannerView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    self.bannerView.localizationImageNamesGroup = @[@"banner1", @"banner2", @"banner3"];
}

- (void)setupCollection {
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    
    self.mainCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.mainCollectionView.backgroundColor = [UIColor whiteColor];
    self.mainCollectionView.showsVerticalScrollIndicator = NO;
    self.mainCollectionView.showsHorizontalScrollIndicator = NO;
    self.mainCollectionView.delegate = self;
    self.mainCollectionView.dataSource = self;
    [self.mainCollectionView registerClass:BookMallMainCell.class forCellWithReuseIdentifier:@"cell"];
    [self.mainCollectionView registerClass:BookMallBannerHeader.class forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"banner"];
    [self.mainCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([BookCollectCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([BookCollectCell class])];
    [self.mainCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([FooterCollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([FooterCollectionReusableView class])];
    [self.mainCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([RecommendCollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([RecommendCollectionReusableView class])];
    [self.view addSubview:self.mainCollectionView];
}

- (void)loadData {
    
    NSString *filePath = [NSBundle.mainBundle pathForResource:@"homeDataCache.plist" ofType:nil];
    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
    self.modelsArray = [NSArray yy_modelArrayWithClass:HomeMenuModel.class json:dict[@"data"]];
    for (NSInteger i = 0; i < self.modelsArray.count; i++) {
        self.modelsArray[i].imageName = [NSString stringWithFormat:@"home_%ld", self.modelsArray[i].sortCode.integerValue - 1];
    }
    HomeMenuModel *bookModel = [HomeMenuModel new];
    bookModel.moduleName = @"书架";
    bookModel.imageName = @"bookLib";
    bookModel.sortCode = @"888";
    
    HomeMenuModel *mineModel = [HomeMenuModel new];
    mineModel.moduleName = @"我的";
    mineModel.imageName = @"home_8";
    mineModel.sortCode = @"999";
    
    NSMutableArray *temp = self.modelsArray.mutableCopy;
    [temp addObject:bookModel];
    [temp addObject:mineModel];
    self.modelsArray = temp.copy;
    
    [self.mainCollectionView reloadData];
    
    MJWeakSelf;
    [CXDNetHelp getRequestWithURLString:@"http://service.wenqujingdian.com/wqjd/app/GetModuleOfVersion" parameters:@{@"appId":@"ios",@"appType":@"ios",@"gradleVersion":@(2)} success:^(id  _Nullable responseObject) {
        
        self.modelsArray = [NSArray yy_modelArrayWithClass:[HomeMenuModel class] json:responseObject[@"data"]];
        if ([self.modelsArray.firstObject.moduleName isEqualToString:@"首页"]) {
            NSMutableArray *arrM = self.modelsArray.mutableCopy;
            [arrM removeObjectAtIndex:0];
            self.modelsArray = arrM.copy;
        }
        for (NSInteger i = 0; i < self.modelsArray.count; i++) {
            self.modelsArray[i].imageName = [NSString stringWithFormat:@"home_%ld", self.modelsArray[i].sortCode.integerValue - 1];
        }
        HomeMenuModel *bookModel = [HomeMenuModel new];
        bookModel.moduleName = @"书架";
        bookModel.imageName = @"bookLib";
        bookModel.sortCode = @"888";
        
        HomeMenuModel *mineModel = [HomeMenuModel new];
        mineModel.moduleName = @"扫码";
        mineModel.imageName = @"home_8";
        mineModel.sortCode = @"999";
        
        NSMutableArray *temp = self.modelsArray.mutableCopy;
        [temp addObject:bookModel];
        [temp addObject:mineModel];
        self.modelsArray = temp.copy;
        [weakSelf.mainCollectionView reloadData];
        
    } failure:^(NSError * _Nullable error) {
        
    }];
    
    [CXDNetHelp getRequestWithURLString:RecomendBookURL parameters:nil success:^(id  _Nullable responseObject) {
        NSLog(@"%@   %@",RecomendBookURL,responseObject);
        _recommentArray = [NSArray yy_modelArrayWithClass:[BookDetailModel class] json:responseObject];
        [self.mainCollectionView reloadData];
    } failure:^(NSError * _Nullable error) {
        
    }];
    
    [CXDNetHelp getRequestWithURLString:ReadRankURL parameters:nil success:^(id  _Nullable responseObject) {
        _rankArray = [NSArray yy_modelArrayWithClass:[BookDetailModel class] json:responseObject];
        [self.mainCollectionView reloadData];
    } failure:^(NSError * _Nullable error) {
        
    }];
    
    [CXDNetHelp getRequestWithURLString:NewBookShelfURL parameters:nil success:^(id  _Nullable responseObject) {
        _BookNewArray = [NSArray yy_modelArrayWithClass:[BookDetailModel class] json:responseObject];
        [self.mainCollectionView reloadData];
    } failure:^(NSError * _Nullable error) {
        
    }];
}

- (void)moreBtnAction:(UIButton *)sender {
    if (sender.indexPath.section == 1) {
        RecommendBookVC *bookVC = [[RecommendBookVC alloc] init];
        [self.navigationController pushViewController:bookVC animated:YES];
    }else if (sender.indexPath.section == 2) {
        RankBookVC *bookVC = [[RankBookVC alloc] init];
        [self.navigationController pushViewController:bookVC animated:YES];
    }else if (sender.indexPath.section == 3) {
        BookNeewVC *bookVC = [[BookNeewVC alloc] init];
        [self.navigationController pushViewController:bookVC animated:YES];
    }
}

#pragma mark - UICollectionDelegate && UICollectionDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 4;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (section == 0) {
        return self.modelsArray.count;
    } else if (section == 1) {
        return self.recommentArray.count > 6? 6: self.recommentArray.count;
    } else if (section == 2) {
        return self.rankArray.count > 6? 6: self.rankArray.count;
    } else {
        return self.BookNewArray.count > 6? 6: self.BookNewArray.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0) {
        BookMallMainCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
        cell.adapterViewModel = self.modelsArray[indexPath.item];
        return cell;
    }
    
    BookCollectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([BookCollectCell class]) forIndexPath:indexPath];
    cell.backView.hidden = YES;
    BookDetailModel *tempModel;
    if (indexPath.section == 1) {
        tempModel = _recommentArray[indexPath.item];
    }else if (indexPath.section == 2) {
        tempModel = _rankArray[indexPath.item];
    }else if (indexPath.section == 3) {
        tempModel = _BookNewArray[indexPath.item];
    }
    [cell.bookImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",RootHomeURL,tempModel.spic]]];
    cell.nameLabel.text = tempModel.news_tit;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        RecommendCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([RecommendCollectionReusableView class]) forIndexPath:indexPath];
        if (indexPath.section == 0) {
            BookMallBannerHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"banner" forIndexPath:indexPath];
            if (header.subviews.count == 0) {
                [header addSubview:self.bannerView];
                self.bannerView.frame = header.bounds;
            }
            return header;
        } else if (indexPath.section == 1) {
            view.titleLabel.text = @"推荐图书";
            view.subLabel.text = @"Recommended Books";
            return view;
        }else if (indexPath.section == 2) {
            view.titleLabel.text = @"排行榜";
            view.subLabel.text = @"Ranking List";
            return view;
        }else if (indexPath.section == 3) {
            view.titleLabel.text = @"新书上架";
            view.subLabel.text = @"New books";
            return view;
        }
    } else {
        FooterCollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:NSStringFromClass([FooterCollectionReusableView class]) forIndexPath:indexPath];
        view.moreBtn.indexPath = indexPath;
        [view.moreBtn addTarget:self action:@selector(moreBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        return view;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        
        NSString *nameString = self.modelsArray[indexPath.item].moduleName;
        BaseViewController *vc = nil;
        if ([nameString isEqualToString:@"阅享馆"]) {
            vc = [MallBookViewController new];
        }else if ([nameString isEqualToString:@"期刊馆"]) {
            vc = [PeriodicalViewController new];
        }else if ([nameString isEqualToString:@"听书馆"]) {
            vc = [MallListenViewController new];
        }else if ([nameString isEqualToString:@"日习馆"]) {
            vc = [MallNewspaperViewController new];
        }else if ([nameString isEqualToString:@"体验馆"]) {
            vc = [VoiceBookViewController new];
        }else if ([nameString isEqualToString:@"书友会"]){
            vc = [ReadAppBookFirendVC new];
        }
        vc.title = nameString;
        [self.navigationController pushViewController:vc animated:YES];
        
        UITabBarController *tabber = (UITabBarController *)UIApplication.sharedApplication.keyWindow.rootViewController;
        if (self.modelsArray[indexPath.item].sortCode.integerValue == 888) {
            tabber.selectedIndex = 0;
        } else if (self.modelsArray[indexPath.item].sortCode.integerValue == 999) {
//            tabber.selectedIndex = 2;
            ScanQRCodeVC *vc = [ScanQRCodeVC new];
            [self presentViewController:vc animated:YES completion:nil];
        }
        
    } else {
        
        BookDetailShowViewController *detailVC = [[BookDetailShowViewController alloc] init];
        BookDetailModel *tempModel;
        if (indexPath.section == 1) {
            tempModel = _recommentArray[indexPath.item];
        }else if (indexPath.section == 2) {
            tempModel = _rankArray[indexPath.item];
        }else if (indexPath.section == 3) {
            tempModel = _BookNewArray[indexPath.item];
        }
        detailVC.navigationItem.title = tempModel.news_tit;
        detailVC.bookId = tempModel.bookID;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        return CGSizeMake(80, 80);
    } else {
        return CGSizeMake((kScreenWidth - 10) / 3, 150);
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    
    if (section == 0) {
        return CGSizeZero;
    }
    return CGSizeMake(kScreenWidth, 65);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return CGSizeMake(kScreenWidth, 113 * kScreenWidthScale);
    }
    return CGSizeMake(kScreenWidth, 80);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    
    if (section == 0) {
        return (kScreenWidth - 20 - 80 * 4) / 3;
    }
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    if (section == 0) {
        return UIEdgeInsetsMake(0, 10, 0, 10);
    }
    return UIEdgeInsetsZero;
}

@end
